package com.joe.demo.nio.buffer;

import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-28
 */
@Slf4j
public class TestByteBufferString {
    public static void main(String[] args) {

        // 1. 字符串 转为 byteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put("hello world".getBytes(StandardCharsets.UTF_8));
        buffer.flip();
        log.info("{}", (char)buffer.get());

        // 2. charset
        ByteBuffer bufferCharset = StandardCharsets.UTF_8.encode("hello world");
        log.info("{}", (char)bufferCharset.get());

        // 3. wrap
        ByteBuffer bufferWrap = ByteBuffer.wrap("hello world".getBytes(StandardCharsets.UTF_8));
        log.info("{}", (char)bufferWrap.get());

        CharBuffer charBuffer = StandardCharsets.UTF_8.decode(bufferWrap);
        log.info("{}", charBuffer);
    }
}
